package cn.com.lanou.wechat.service.impl;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.lanou.util.IpUtil;
import cn.com.lanou.wechat.dao.WechatMapper;
import cn.com.lanou.wechat.service.WechatService;

@Service
public class WechatServiceImpl implements WechatService {

	@Autowired
	private WechatMapper wechatMapper;
	
	@Override
	public String findToken() {
		
		return wechatMapper.findToken();
	}
	@Override
	public String creatMenu(String access_token) {
//		String access_token = wechatService.findToken();
		String menu = "{" + "\"button\":[" 
				+ " {"
				+ "      \"name\":\"小区业主\"," + " \"sub_button\":["
				+ "      {" + "          \"type\":\"view\","
				+ "          \"name\":\"百度\","
				+ "          \"url\":\"https://www.baidu.com\"" + "       },"
				+ "       {" + "          \"type\":\"view\","
				+ "          \"name\":\"填写订单\","
				+ "          \"url\":\"http://9d83b614.ngrok.io/owner/owner/toReclamationOrder.do\"" + "       },"
				+ "       {" + "          \"type\":\"view\","
				+ "          \"name\":\"订单列表\","
				+ "          \"url\":\"http://9d83b614.ngrok.io/owner/owner/reclamationOrderList.do\"" + "}]" + "  },"
				+ " {"
				+ "      \"name\":\"回收员\"," + " \"sub_button\":["
				+ "      {" + "          \"type\":\"view\","
				+ "          \"name\":\"绑定微信\","
				+ "          \"url\":\""+IpUtil.IP+"/fgd/bind/goBind\"" + "       },"
				+ "       {" + "          \"type\":\"view\","
				+ "          \"name\":\"订单查看\","
				+ "          \"url\":\""+IpUtil.IP+"/fgd/order/goOrder\"" + "       },"
				+ "       ]" + "  }"
				+ "]" + "}";
		System.out.println(menu);
		String action = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="
				+ access_token;
		String message = "";
		try {
			URL url = new URL(action);
			HttpURLConnection http =   (HttpURLConnection) url.openConnection();    
			
			http.setRequestMethod("POST");        
			http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");    
			http.setDoOutput(true);        
			http.setDoInput(true);
	 
			http.connect();
			OutputStream os= http.getOutputStream();    
			os.write(menu.getBytes("UTF-8"));//传入参数    
			os.flush();
			os.close();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			message = new String(jsonBytes,"UTF-8");
			System.out.println("返回信息"+message);
           } catch (Exception e) {
               e.printStackTrace();
           }
		return message;
//		log.info(message);
		
	}

}
